from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, UpdateAPIView
from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import merge_cookie_redis_cart
from goods.models import SKU
from . import serializers
from .models import User
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework import mixins
from rest_framework.generics import CreateAPIView
from rest_framework.viewsets import GenericViewSet
from django_redis import get_redis_connection


class CheckUsernameView(APIView):
    def get(self, request, username):

        # 1.根据用户名查询，用户数量
        count = User.objects.filter(username=username)

        # 2.返回响应
        data = {
            "count": count
        }
        return Response(data, status=status.HTTP_200_OK)


class CheckMobileView(APIView):
    def get(self, request, mobile):

        # 1.根据手机查询，用户数量
        count = User.objects.filter(mobile=mobile)

        # 2.返回响应
        data = {
            "count": count
        }
        return Response(data, status=status.HTTP_200_OK)


class RegisterUerView(CreateAPIView):   # CreateAPIView(三级视图)
# class RegisterUerView(mixins.CreateModelMixin, GenericAPIView):

    serializer_class = serializers.RegisterUerSerializer

    # def post(self, request):
        # 一、只继承自了 GenericAPIView（二级视图）
        # # 1.获取参数
        # dict_data = request.data
        #
        # # 2.创建序列化器， 校验
        # serializer = self.get_serializer(data = dict_data)
        # serializer.is_valid(raise_exception=True)
        #
        # # 3.数据入库
        # serializer.save()
        #
        # # 4.返回响应
        # return Response(serializer.data, status=status.HTTP_201_CREATED)

        # 二、使用mixin + GenericAPIView
        # return self.create(request)


class UserInfoView(RetrieveAPIView):
    serializer_class = serializers.UserInfoSerializer
    permission_classes = [IsAuthenticated]  # 认证的用户

    def get_object(self):
        return self.request.user

    # def get(self,request):
    #     #一, 单纯使用二级视图实现
    #     # #1,获取用户对象(或者request.user)
    #     # user =  self.get_object()
    #     #
    #     # #2,创建序列化对象
    #     # serializer = self.get_serializer(instance=user)
    #     #
    #     # #3,返回数据
    #     # return Response(serializer.data)
    #
    #     #二,二级视图配合mixin
    #     return self.retrieve(request)


class EmailSendView(UpdateAPIView):
    serializer_class = serializers.EmailSendSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

    # def put(self, request):
    #     # 一. 单纯使用二级视图实现
    #     # 1.获取数据
    #     dict_data = request.data
    #     user = self.get_object()
    #
    #     # 2.获取序列化器
    #     serializer = self.get_serializer(isinstance=user, data=dict_data)
    #
    #     # 3.校验，入库
    #     serializer.is_valid(raise_exeption=True)
    #     serializer.save()
    #     # 4.返回
    #     return Response(serializer.data)
    #
    #     #二,二级视图配合mixin
    #     return self.update(request)


class EmailActiveView(APIView):
    def get(self, request):
        # 1.获取参数token  query_params: 获取请求行里面的数据   data: 获取请求体里面的数据
        token = request.query_params.get("token")

        # 2.为空校验
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user = User.decode_token(token)
        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 4.数据入库（修改email_active属性）
        user.email_active = True
        user.save()

        # 5.返回响应
        return Response(status=status.HTTP_200_OK)

class AddressView(mixins.CreateModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.DestroyModelMixin,
                  GenericViewSet):
    serializer_class = serializers.AddressSerializer

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request):
        # 1.获取用户地址信息
        queryset = self.get_queryset()

        # 2.获取序列化器
        serializer = self.get_serializer(instance=queryset, many=True)

        # 3.返回
        return Response({
            "addresses": serializer.data,
            "limit": 20,
            "default_address_id": request.user.default_address_id,
        })

    # 1.重写地址创建方法，判断用户的地址是否已经达到20个了
    def create(self, request, *args, **kwargs):
        # # 1.获取参数
        # dict_data = request.data
        #
        # # 2.获取序列化器
        # serializer = self.get_serializer(data=dict_data)
        #
        # # 3.校验入库
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # # 4.返回
        # return Response(serializer.data)

        # 1.获取用户地址数量
        count = request.user.addresses.filter(is_deleted=False).count()

        # 2.判断地址数量
        if count >= 21:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3.调用父类防方法即可
        return super(AddressView, self).create(request, *args, **kwargs)


    # 2.更改用户默认地址
    @action(methods=["put"], detail=True)  # 格式： addresses/pk/status
    def status(self, request, pk):
        request.user.default_address_id = pk
        request.user.save()
        return Response(status=status.HTTP_200_OK)


    # 3.修改地址的标题
    @action(methods=["put"], detail=True)   # 格式： addresses/pk/title
    def title(self, request, pk):
        # 1.获取参数
        dict_data = request.data
        self.get_object()
        address = self.get_object()

        # 2.创建序列化器
        serializer = serializers.AddressTitleSerializer(instance=address, data=dict_data)

        # 3.校验数据， 入库
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 4.返回
        return Response(serializer.data)

    # 4.重写destroy方法， 为了逻辑删除
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

class TestView(APIView):

    def get(self, request, name, age):
        print(self.kwargs)  # 获取的就是地址中携带的资源参数
        return Response("%s, %s" % (name, age))


class UserBrowerHistory(CreateAPIView):
    serializer_class = serializers.UserBrowerHistorySerializer

    # 二级：GenericAPIView
    # def post(self, request):
    #     # 1.获取参数
    #     dict_data = request.data
    #
    #     # 2.获取序列化器， 校验
    #     serializer = self.get_serializer(data=dict_data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 3.入库（保存到redis中）
    #     serializer.save()
    #
    #     # 4.返回
    #     return Response(serializer.data)

    def get(self, request):

        # 1.获取redis中的数据
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s" % request.user.id, 0, 4)

        # 2.拼接数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "default_image_url": sku.default_image_url,
                "name": sku.name,
                "price": sku.price,
                "comments": sku.comments,
                "id": sku.id
            }
            sku_list.append(sku_dict)

        # 3.返回
        return Response(sku_list)


# 重写登陆类视图
class UserObtainJSONWebToken(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):

        # 1.调用父类方法
        response = super().post(request, *args, **kwargs)

        # 2.获取序列化器
        serializer = self.get_serializer(data=request.data)

        # 3.判断是否认证成功
        if serializer.is_valid():
            # 3.1获取user对象
            user = serializer.validated_data.get("user")

            # 3.2合并购物车
            response = merge_cookie_redis_cart(request, user, response)


        return response















